package com.xxxx.server.service.impl;


import com.alibaba.excel.metadata.BaseRowModel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.xxxx.server.mapper.EmployeeMapper;
import com.xxxx.server.mapper.MailLogMapper;
import com.xxxx.server.page.EmployeeExcel;
import com.xxxx.server.page.RespPageBean;
import com.xxxx.server.pojo.*;

import com.xxxx.server.service.IEmployeeService;

//import com.xxxx.server.utils.DateUtil;
//import com.xxxx.server.utils.ExcelUtil;
import com.xxxx.server.utils.ExcelUtil;
import org.apache.poi.ss.usermodel.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;



import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements IEmployeeService {

    public final static Logger logger = LoggerFactory.getLogger(IEmployeeService.class);
    SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
    SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
    DecimalFormat decimalFormat = new DecimalFormat("##.00");

    @Autowired
    private  EmployeeMapper employeeMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private MailLogMapper mailLogMapper;


    /**
     * 查询所有员工对象（分页）
     * @param currentPage
     * @param size
     * @param employee
     * @param beginDateScope
     * @return
     */
    //展示所有数据
    @Override
    public RespPageBean getEmployeeByPage(Integer currentPage
            , Integer size, Employee employee, LocalDate[] beginDateScope) {
        //开启分页
        Page<Employee> page = new Page<>(currentPage,size);
        IPage<Employee> employeeByPage = employeeMapper.getEmployeeByPage(page, employee, beginDateScope);
        RespPageBean respPageBean = new RespPageBean(employeeByPage.getTotal(),employeeByPage.getRecords());
        return respPageBean;
        /*if (currentPage != null && size != null) {
            currentPage = (currentPage - 1) * size;
        }
        List<Employee> data = employeeMapper.getEmployeeByPage(currentPage, size, employee, beginDateScope);
        Long total = employeeMapper.getTotal(employee, beginDateScope);
        RespPageBean bean = new RespPageBean();
        bean.setData(data);
        bean.setTotal(total);
        return bean;*/
    }

    /**
     * 获取工号
     * @return
     */
    @Override
    public RespBean maxWorkID() {
        //通过sql语句查询到最后一个workId
        List<Map<String, Object>> maps = employeeMapper.selectMaps(new QueryWrapper<Employee>().select("max(workID)"));
        //将查询到的最后一个workId + 1
        int maxWorkId = Integer.parseInt(maps.get(0).get("max(workID)").toString()) + 1;
        //此格式化目的是不让前面的零消失，比如00000101，如果不设置此格式化，输出结果就为101
        String formatMaxWorkId = String.format("%08d", maxWorkId);
        return RespBean.success(null,formatMaxWorkId);
    }

    /**
     * 添加员工
     * @param employee
     * @return
     */
    @Override
    public RespBean addEmp(Employee employee) {
        //处理合同期限，单位：年保留两位小数
        LocalDate beginContract = employee.getBeginContract();
        LocalDate endContract = employee.getEndContract();
        //计算合同起始日期和到同终止日期的天数
        long days = beginContract.until(endContract, ChronoUnit.DAYS);
        DecimalFormat decimalFormat = new DecimalFormat("##.00");
        employee.setContractTerm(Double.parseDouble(decimalFormat.format(days/365.00)));
        System.out.println(employee);
        if (1== employeeMapper.insert(employee)){
            Employee emp = employeeMapper.getEmployee(employee.getId()).get(0);
            //数据库记录发送的信息
            String msgId = UUID.randomUUID().toString();//消息ID
            /*String msgId = "123456";//消息ID*/
            MailLog mailLog = new MailLog();
            mailLog.setMsgId(msgId);
            mailLog.setEid(employee.getId());
            mailLog.setStatus(0);
            mailLog.setCount(0);
            mailLog.setExchange(MailConstants.MAIL_EXCHANGE_NAME);
            mailLog.setRouteKey(MailConstants.MAIL_ROUTING_KEY_NAME);
            mailLog.setTryTime(LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT));
            mailLog.setCreateTime(LocalDateTime.now());
            mailLog.setUpdateTime(LocalDateTime.now());
            mailLogMapper.insert(mailLog);//消息入库
            //发送信息
            rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,emp,
                    new CorrelationData(msgId));
            //rabbitTemplate.convertAndSend("mail.welcome",emp);
            return  RespBean.success("员工数据插入成功！");
        }
        return  RespBean.error("员工数据插入失败！");
    }

    /**
     * 根据ID查询员工
     * @param id
     * @return
     */

    @Override
    public List<Employee> getEmployee(Integer id) {
        return employeeMapper.getEmployee(id);
    }

    /**
     * 查询所有员工账套
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public RespPageBean getEmployeeWithSalary(Integer currentPage, Integer pageSize) {
        //开启分页
        Page<Employee> page = new Page<>(currentPage,pageSize);

        IPage<Employee> employeeIPage = employeeMapper.getEmployeeWithSalary(page);

        //获取总页数和employee对象
        RespPageBean respPageBean = new RespPageBean(employeeIPage.getTotal(),employeeIPage.getRecords());
        return respPageBean;
    }

/*
    //更新员工信息
    @Override
    public Integer updateEmployeeById(Employee employee) {
        return employeeMapper.updateEmployeeById(employee);
    }


    //导入数据批量增加
    @Override
    public Integer addEmployees(List<Object> list) {
        return employeeMapper.addEmployees(list);
    }


    //导出数据
    @Override
    public List<Employee> findAllEmployee() {
        return employeeMapper.findAllEmployee();
    }

    //导入数据
    @Override
    public List<Object> importEmployeeExcel(MultipartFile excel, BaseRowModel baseRowModel, int headLineNum) {
        List<Object> list = ExcelUtil.readExcel(excel, baseRowModel, headLineNum);
        Employee employee = new Employee();
        for (int i = 0; i < list.size(); i++) {
            EmployeeExcel employeeExcel = (EmployeeExcel) list.get(i);
            employee.setId(Integer.valueOf(employeeExcel.getId()));
            employee.setName(employeeExcel.getName());
            employee.setGender(employeeExcel.getGender());
            employee.setPhone(employeeExcel.getPhone());
            //出生日期
            String birthday = employeeExcel.getBirthday();
            //LocalDateTime b = DateUtil.getLocalDateTime(birthday);
            //employee.setBirthday(b);

            employee.setIdCard(employeeExcel.getIdCard());
            employee.setWedlock(employeeExcel.getWedlock());
            employee.setPhone(employeeExcel.getPhone());
            employee.setNationId(Integer.valueOf(employeeExcel.getNationId()));
            employee.setNativePlace(employeeExcel.getNativePlace());
            employee.setPoliticId(Integer.valueOf(employeeExcel.getPoliticId()));
            employee.setEmail(employeeExcel.getEmail());
            employee.setPhone(employeeExcel.getPhone());
            employee.setAddress(employeeExcel.getAddress());
            employee.setDepartmentId(Integer.valueOf(employeeExcel.getDepartmentId()));
            employee.setJobLevelId(Integer.valueOf(employeeExcel.getJobLevelId()));
            employee.setPosId(Integer.valueOf(employeeExcel.getPosId()));
            employee.setEngageForm(employeeExcel.getEngageForm());
            employee.setTiptopDegree(employeeExcel.getTiptopDegree());
            employee.setSpecialty(employeeExcel.getSpecialty());
            employee.setSchool(employeeExcel.getSchool());
            //入职日期
            String beginDate = employeeExcel.getBeginDate();
            //LocalDateTime bengin = DateUtil.getLocalDateTime(beginDate);
            //employee.setBirthday(bengin);

            employee.setWorkState(employeeExcel.getWorkState());
            employee.setWorkID(employeeExcel.getWorkID());
            employee.setContractTerm(Double.valueOf(employeeExcel.getContractTerm()));
            employee.setWorkState(employeeExcel.getWorkState());
            //转正日期
            String conversionTime = employeeExcel.getConversionTime();
            //LocalDateTime conversion = DateUtil.getLocalDateTime(conversionTime);
            //employee.setBirthday(conversion);
            //离职日期
            String notWorkDate = employeeExcel.getNotWorkDate();
            //LocalDateTime notWork = DateUtil.getLocalDateTime(notWorkDate);
            //employee.setBirthday(notWork);
            //合同起始
            String beginContract = employeeExcel.getBeginContract();
            //LocalDateTime contract = DateUtil.getLocalDateTime(beginContract);
            //employee.setBirthday(contract);
            //合同终止
            String endContract = employeeExcel.getEndContract();
            //LocalDateTime end = DateUtil.getLocalDateTime(endContract);
            //employee.setBirthday(end);

            employee.setWorkAge(Integer.valueOf(employeeExcel.getWorkAge()));
            employee.setSalaryId(Integer.valueOf(employeeExcel.getSalaryId()));
            //String birthday = employeeExcel.getBirthday();
            //LocalDateTime b = DateUtil.getLocalDateTime(birthday);
            //employee.setBirthday(b);


            //    可以写很多处理后的数据
            //employee.setCredits(10.8f);
            //employee.setCreateTime(LocalDateTime.now());
            employeeMapper.insert(employee);
        }
        return ExcelUtil.readExcel(excel, new EmployeeExcel(), headLineNum);
    }*/
/*
    //根据ID删除员工信息
    @Override
    public Integer removeEmployeeById(Integer id) {
        return employeeMapper.deleteEmployeeById(id);
    }



    //添加员工信息
    @Override
    public Integer saveEmployee(EmployeeAdd employeeAdd) {
        Date beginContract = employeeAdd.getBeginContract();
        Date endContract = employeeAdd.getEndContract();
        Employee employee = new Employee();

        double month = (Double.parseDouble(yearFormat.format(endContract)) - Double.parseDouble(yearFormat.format(beginContract))) * 12 + (Double.parseDouble(monthFormat.format(endContract)) - Double.parseDouble(monthFormat.format(beginContract)));
        employeeAdd.setContractTerm(Double.parseDouble(decimalFormat.format(month / 12)));
        int result = employeeMapper.addEmployeeOne(employeeAdd);
        //如果添加成功就获取到邮箱 发送邮件
        if (result == 1) {
            //发送邮件
            sendHtmlMail(employee.getEmail(),"主题：你好text邮件","内容：第一封text邮件");
        }
        return result;
    }


    //按照员工的 id对员工发送邮件
    public Employee getEmployeeById(Integer empId) {
        return employeeMapper.getEmployeeById(empId);
    }

    //最大工号  完成添加时的自增
    public Integer maxWorkID() {
        return employeeMapper.maxWorkID();
    }


    //配置文件中我的QQ邮箱 邮件发送者
    @Value("${spring.mail.from}")
    private String from;

    //发送邮件
    public void sendHtmlMail(String to, String subject, String content) {
        //获取Message对象
        SimpleMailMessage message = new SimpleMailMessage();
        Employee employee = new Employee();
        try {
            //邮件发送人
            message.setFrom(from);
            //邮件接收人
            message.setTo(to);
            //设置抄送地址，如需设置多个地址，可以使用setCc(String[] cc)方法
            message.setCc(employee.getEmail());
            //设置暗送地址，如需设置多个地址，可以使用setBcc(String[] bcc)方法
            message.setBcc(employee.getEmail());
            //邮件主题
            message.setSubject(subject);
            //邮件内容，html格式
            message.setText(content);
            //发送
            mailSender.send(message);
            //日志信息
            logger.info("邮件已经发送。");
        } catch (Throwable e) {
            logger.error("邮件发送失败", e);
        }

    }*/



}
